package com.xrh.core.annotation;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.Arrays;
import java.util.Collection;
import java.util.stream.Collectors;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * @function 整形范围校验
 * @author 肖荣辉
 * @date 2023年12月8日
*/
@Documented
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
@Retention(RUNTIME)
@Constraint(validatedBy = {InIntValidation.InValidator.class})
@Repeatable(InIntValidation.List.class)
public @interface InIntValidation {
    String message() default "不在指定值域";

    int[] value() default {};

    //默认不允许为空
    boolean nullable() default false;

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    @Documented
    @Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
    @Retention(RUNTIME)
    @interface List {
        InIntValidation[] value();
    }

    class InValidator implements ConstraintValidator<InIntValidation, Object> {

        private InIntValidation inValidation;

        @Override
        public void initialize(InIntValidation inValidation) {
            this.inValidation = inValidation;
        }

        @Override
        public boolean isValid(Object value, ConstraintValidatorContext context) {
            if (value == null) {
                return inValidation.nullable();
            }
            int[] inValues = inValidation.value();

            if (value instanceof Collection) {
                //集合类型的，则校验注解中的value必须全部包含传入的value，即传入的值为校验类的子集
                return CollUtil.containsAll(Arrays.stream(inValues).boxed().collect(Collectors.toList()), (Collection<?>) value);
            }
            if (value instanceof Integer) {
                //Integer类型的，则校验注解中的value必须包含传入的value
                return ArrayUtil.contains(inValues, (Integer) value);
            }
            //其他情况，如参数类型不对，返回false
            return false;
        }
    }
}